package com.rightsidetech.http.controller.userApp.address;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.commom.utils.HttpClient;
import com.rightsidetech.commom.utils.StringUtil;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.aspect.Token;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.user.dtos.requst.IdReq;
import com.rightsidetech.user.dtos.requst.UserAddAddressReq;
import com.rightsidetech.user.dtos.requst.UserUpdateAddressReq;
import com.rightsidetech.user.dtos.response.UserAddressResp;
import com.rightsidetech.user.service.UserAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "用户地址相关api")
@RestController
@RequestMapping("/userApp/address")
@ShenyuSpringMvcClient(path = "/userApp/address/**")
@Slf4j
public class UserAddressController extends BaseController {

    @Resource
    private UserAddressService userAddressService;

    @Value("${restapi.amap.addressUrl}")
    private String addressUrl;
    @Value("${restapi.amap.key}")
    private String amapKey;

    @Log
    @Token
    @PostMapping("/add")
    @ApiOperation("添加地址")
    public ResponseData save(@RequestBody UserAddAddressReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        //查询省市区
        Map map = new HashMap<>();
        map.put("key", amapKey);
        map.put("address", req.getAddress());
        JSONObject jsonObject = JSON.parseObject(HttpClient.sendGet(addressUrl, map));
        if (!StringUtil.isNullorEmpty(jsonObject) && jsonObject.getString("status").equals("1") && !StringUtil.isNullorEmpty(jsonObject.get("geocodes"))) {
            JSONArray jsonArray = jsonObject.getJSONArray("geocodes");
            JSONObject jsonObject2 = jsonArray.getJSONObject(0);

            if (!StringUtil.isNullorEmpty(jsonObject2.getString("location"))) {
                req.setProvice(jsonObject2.getString("province"));
                req.setCity(jsonObject2.getString("city"));
                req.setArea(jsonObject2.getString("district"));
            } else {
                return ResponseData.fail("地址错误, 请重新输入地址");
            }
        } else {
            return ResponseData.fail("地址错误, 请重新输入地址");
        }
        Long userInfoId = Long.parseLong(getAttribute());
        return userAddressService.save(req, userInfoId);
    }

    @Log
    @Token
    @PostMapping("/edit")
    @ApiOperation("修改地址")
    public ResponseData edit(@RequestBody UserUpdateAddressReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

//        BigDecimal lon = null;
//        BigDecimal lat = null;
        //根据省市区查询经纬度
        Map map = new HashMap<>();
        map.put("key", amapKey);
        map.put("address", req.getAddress());
        JSONObject jsonObject = JSON.parseObject(HttpClient.sendGet(addressUrl, map));
        if (!StringUtil.isNullorEmpty(jsonObject) && jsonObject.getString("status").equals("1") && !StringUtil.isNullorEmpty(jsonObject.get("geocodes"))) {
            JSONArray jsonArray = jsonObject.getJSONArray("geocodes");
            JSONObject jsonObject2 = jsonArray.getJSONObject(0);

            if (!StringUtil.isNullorEmpty(jsonObject2.getString("location"))) {
                String[] lonAndLat = jsonObject2.getString("location").split(",");
//                lon = new BigDecimal(lonAndLat[0]);
//                lat = new BigDecimal(lonAndLat[1]);
                req.setProvice(jsonObject2.getString("province"));
                req.setCity(jsonObject2.getString("city"));
                req.setArea(jsonObject2.getString("district"));
            } else {
                return ResponseData.fail("地址错误, 请重新输入地址");
            }
        } else {
            return ResponseData.fail("地址错误, 请重新输入地址");
        }
        Long userInfoId = Long.parseLong(getAttribute());
        return userAddressService.update(req, userInfoId);
    }

    @Log
    @Token
    @PostMapping("/editIsDefault")
    @ApiOperation("修改默认地址")
    public ResponseData editIsDefault(@RequestBody IdReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long userInfoId = Long.parseLong(getAttribute());
        return userAddressService.updateIsDefault(userInfoId, req);
    }


    @Log
    @Token
    @PostMapping("/del")
    @ApiOperation("删除地址")
    public ResponseData edit(@RequestBody IdReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long userInfoId = Long.parseLong(getAttribute());
        return userAddressService.del(req,userInfoId);
    }


    @Log
    @Token
    @GetMapping("/list")
    @ApiOperation("地址列表")
    public ResponseData<List<UserAddressResp>> list() throws Exception {
        Long userInfoId = Long.parseLong(getAttribute());
        return userAddressService.list(userInfoId);
    }

//    @Log
//    @Token
//    @GetMapping("/findById")
//    @ApiOperation("查询单个地址")
//    public ResponseData<UserAddressResp> findById(@RequestParam(value = "id",required = true) Long id){
//        if(StringUtil.isNullorEmpty(id)){
//            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), "地址id不能为空");
//        }
//        return ResponseData.success(userAddressService.selectByAddressId(id,Long.parseLong(getAttribute())));
//    }


}
